package top.yrlby.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.yrlby.common.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author BaiYang
 * @time 2022/9/7
 */
/**
 * 文件上传/下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")//文件目录
    private String basePath;


    /**
     * 上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //根据'.'切割字符串获取原始文件名
        String filename = originalFilename.substring(originalFilename.lastIndexOf("."));
        filename = IdWorker.getId()+filename; //雪花算法，生成新文件名
//        filename = UUID.randomUUID().toString()+filename;//UUID，生成新文件名
        File files = new File(basePath);//创建一个目录对象
        if(!files.exists()){//判断当前目录是否存在
            files.mkdirs();//不存在则创建
        }
        try {
            //将文件存入指定目录
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //通过输入流读取图片
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            //通过输出流将图片存入浏览器内存
            ServletOutputStream outputStream =response.getOutputStream();
            response.setContentType("image/jpeg");//指定格式，参数类型是死的

            //循环读取图片，读完则会返回-1
            int len=0;
            byte[] bytes = new byte[1024];//转移的载体，容器
            //做了3件事：(len = fileInputStream.read(bytes)) != -1
            //1、从输入流中读取文件内容放到容器bytes
            //2、read()的返回值赋给了len
            //3、判断len的值，是否读完了（len == -1）
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
